#!/bin/bash -e
# @author Aleksandar Gotev (alex.gotev@mobimesh.it)
# @author Vincenzo Esposito (v.esposito@voismart.it)

. config.conf

BASE_FOLDER=$DOWNLOAD_DIR

PJSIP_BASE_PATH="${BASE_FOLDER}/${PJSIP_DIR_NAME}"
PJSIP_TMP_PATH="/tmp/pjsip"
CONFIG_SITE_PATH="${PJSIP_BASE_PATH}/pjlib/include/pj/config_site.h"
PJSUA_BASE_DIR="${PJSIP_TMP_PATH}/pjsip-apps/src/swig"
PJSUA_GENERATED_SRC_DIR="${PJSUA_BASE_DIR}/java/android/$PJSIP_GENERATED_ROOT_DIR_NAME/src/main/java/"
PJSUA_GENERATED_SO_PATH="${PJSUA_BASE_DIR}/java/android/$PJSIP_GENERATED_ROOT_DIR_NAME/src/main/jniLibs"
FINAL_BUILD_DIR=$PJSIP_BUILD_OUT_PATH
FINAL_BUILD_LIB="${FINAL_BUILD_DIR}/lib"
FINAL_BUILD_LOGS="${FINAL_BUILD_DIR}/logs"

export ANDROID_NDK_ROOT="${BASE_FOLDER}/${NDK_DIR_NAME}"
export PATH="$ANDROID_NDK_ROOT:$PATH"

##############################################################################
############################      FUNCTIONS     ##############################
##############################################################################

function clearBuildDirectory {
    echo "Clear final build folder ..."
    rm -rf "${FINAL_BUILD_DIR}"
    mkdir -p "${FINAL_BUILD_LIB}"
    mkdir -p "${FINAL_BUILD_LOGS}"
}

function setConfigSite {
    echo "Creating config site file for Android ..."
    echo "#define PJ_CONFIG_ANDROID 1" > "$CONFIG_SITE_PATH"
    echo "#define PJMEDIA_HAS_G7221_CODEC 1" >> "$CONFIG_SITE_PATH"
    echo "#include <pj/config_site_sample.h>" >> "$CONFIG_SITE_PATH"
    echo "#define PJMEDIA_HAS_VIDEO 1" >> "$CONFIG_SITE_PATH"
    echo "#define PJMEDIA_AUDIO_DEV_HAS_ANDROID_JNI 0" >> "$CONFIG_SITE_PATH"
    echo "#define PJMEDIA_AUDIO_DEV_HAS_OPENSL 1" >> "$CONFIG_SITE_PATH"
    echo "#define PJSIP_AUTH_AUTO_SEND_NEXT 0" >> "$CONFIG_SITE_PATH"
    echo "#define PJMEDIA_HAS_OPUS_CODEC 1" >> "$CONFIG_SITE_PATH"
    echo "#define PJMEDIA_VIDEO_DEV_HAS_ANDROID 1" >> "$CONFIG_SITE_PATH"

    if [ "${ENABLE_IPV6}" == "1" ]
    then
        echo "#define PJ_HAS_IPV6 1" >> "$CONFIG_SITE_PATH"
    fi

    if [ "${DOWNLOAD_BCG729}" == "1" ]
    then
        echo "#define PJMEDIA_HAS_BCG729 1" >> "$CONFIG_SITE_PATH"
    fi

    if [ "${DOWNLOAD_FFMPEG}" == "1" ]
    then
        echo "#define PJMEDIA_HAS_FFMPEG 1" >> "$CONFIG_SITE_PATH"
        echo "#undef PJMEDIA_USE_OLD_FFMPEG" >> "$CONFIG_SITE_PATH"
    fi

    if [ "${DOWNLOAD_OPENH264}" == "1" ]
    then
        echo "#define PJMEDIA_HAS_OPENH264_CODEC 1" >> "$CONFIG_SITE_PATH"
    fi
}

function buildPjSip {
    arch=$1
    echo "Compile PJSIP for arch $arch ..."
    rm -rf "${PJSIP_TMP_PATH}"
    mkdir -p "${PJSIP_TMP_PATH}"
    cd "${PJSIP_BASE_PATH}"
    cp -r * "${PJSIP_TMP_PATH}"
    cd "${PJSIP_TMP_PATH}"

    args=("--use-ndk-cflags"
        "--with-ssl=${OPENSSL_BUILD_OUT_PATH}/libs/${arch}"
        "--with-openh264=${OPENH264_BUILD_OUT_PATH}/libs/${arch}"
        "--with-opus=${OPUS_BUILD_OUT_PATH}/libs/${arch}"
        "--with-bcg729=${BCG729_BUILD_OUT_PATH}/libs/${arch}")

    APP_PLATFORM=android-${TARGET_ANDROID_API} TARGET_ABI=$arch ./configure-android "${args[@]}" >> "${FINAL_BUILD_LOGS}/${arch}.log" 2>&1

    make dep >>"${FINAL_BUILD_LOGS}/${arch}.log" 2>&1
    make clean >>"${FINAL_BUILD_LOGS}/${arch}.log" 2>&1
    make >>"${FINAL_BUILD_LOGS}/${arch}.log" 2>&1

    echo "Compile PJSUA for arch $arch ..."
    cd "${PJSUA_BASE_DIR}"
    make >>"${FINAL_BUILD_LOGS}/${arch}.log" 2>&1

    echo "Copying PJSUA .so library to final build directory ..."
    mkdir -p "${FINAL_BUILD_LIB}/${arch}"
    # Different versions of PJSIP put .so libs in different directory name
    # using /*/* we assume there is only one directory (whatever its name is)
    # and retrieve all its content (.so libs)
    mv "${PJSUA_GENERATED_SO_PATH}"/*/* "${FINAL_BUILD_LIB}/${arch}"

    if [ -f ${FFMPEG_BUILD_OUT_PATH}/libs/${arch}/lib/libavformat.so ]; then
        echo "Copying FFmpeg .so library to final build directory ..."
        cp ${FFMPEG_BUILD_OUT_PATH}/libs/${arch}/lib/*.so ${FINAL_BUILD_LIB}/${arch}/
    fi

    if [ -f ${OPENH264_BUILD_OUT_PATH}/libs/${arch}/lib/libopenh264.so ]; then
        echo "Copying OpenH264 .so library to final build directory ..."
        cp ${OPENH264_BUILD_OUT_PATH}/libs/${arch}/lib/libopenh264.so ${FINAL_BUILD_LIB}/${arch}/
    fi
}

function copyPjSuaJava {
    echo "Copying PJSUA2 java bindings to final build directory ..."
    cp -r "${PJSUA_GENERATED_SRC_DIR}" "${FINAL_BUILD_DIR}"
    rm -r "${PJSIP_TMP_PATH}"
}

function clearToolsDirectory {
    if [ "$REMOVE_TOOLS" == "1" ]
    then
        echo ""
        echo "Cleaning up tools ..."
        cd $BASEDIR
        rm -r tools
        echo "Finished cleaning up tools"
    fi
}

function setPermissions {
    if [ "$SET_PERMISSIONS" == "1" ] && [ "$OWNER" != "" ]
    then
        echo ""
        echo "Setting permissions on $BUILD_DIR for user $OWNER"
        chown $OWNER -R $BUILD_DIR
        echo "Finished Setting permissions"
    elif [ "$SET_PERMISSIONS" == "1" ] || [ "$OWNER" != "" ]
    then
        echo "You must set both the toggle [SET_PERMISSIONS] to 1 and the name of the user [OWNER] that should own the files"
    fi
}

##############################################################################
############################        MAIN          ############################
##############################################################################

# Clearing the build output directory
clearBuildDirectory

# Create config_site file
setConfigSite

# Build PjSip for each ARCH specified in config.conf
for arch in "${TARGET_ARCHS[@]}"
do
    buildPjSip $arch
done

# Copy PjSua Java Bindings into final build output directory
copyPjSuaJava

# Delete the tools directory
clearToolsDirectory

# Setting Permission on build output directory
setPermissions

echo "Finished! Check the generated output in ${FINAL_BUILD_DIR}"
